<template>
  <div class="harvest-container">
    <!-- 顶部工具栏 -->
    <el-card class="search-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <div class="title">
            <el-icon><i class="el-icon-collection-tag" /></el-icon>
            <span>收获记录管理</span>
          </div>
          <div class="actions">
            <el-button type="success" @click="handleAdd">
              <el-icon><Plus /></el-icon>
              新增收获记录
            </el-button>
            <el-button @click="toggleFold" text type="primary">
              <el-icon v-if="folded"><el-icon-arrow-down /></el-icon>
              <el-icon v-else><el-icon-arrow-up /></el-icon>
            </el-button>
          </div>
        </div>
      </template>

      <!-- 搜索区域 -->
      <el-form :inline="true" :model="searchObj" label-width="80px" class="search-form">
        <el-row :gutter="12">
          <el-col :xs="24" :sm="12" :md="8" :lg="6">
            <el-form-item label="水果">
              <el-select
                  v-model="searchObj.fruit_id"
                  placeholder="选择水果"
                  clearable
                  filterable
                  :loading="fruitLoading"
                  style="min-width: 180px"
              >
                <el-option
                    v-for="f in fruits"
                    :key="f.fruit_id"
                    :label="f.fruit_name"
                    :value="f.fruit_id"
                />
              </el-select>
            </el-form-item>
          </el-col>

<!--          <el-col :xs="24" :sm="12" :md="8" :lg="6">-->
<!--            <el-form-item label="收获时间">-->
<!--              &lt;!&ndash; 搜索条件也用 datetime，始终是 'YYYY-MM-DD HH:mm:ss' 字符串 &ndash;&gt;-->
<!--              <el-date-picker-->
<!--                  v-model="searchObj.harvest_date"-->
<!--                  type="datetime"-->
<!--                  placeholder="选择收获时间"-->
<!--                  clearable-->
<!--                  style="width: 100%"-->
<!--                  value-format="YYYY-MM-DD HH:mm:ss"-->
<!--              />-->
<!--            </el-form-item>-->
<!--          </el-col>-->

          <el-col :xs="24" :sm="12" :md="8" :lg="6">
            <el-form-item label="批次号">
              <el-input v-model="searchObj.batch_no" placeholder="请输入批次号" clearable />
            </el-form-item>
          </el-col>

          <el-col :xs="24" :sm="12" :md="8" :lg="6">
            <el-form-item label=" ">
              <el-space>
                <el-button type="primary" @click="loadData" :loading="loading">
                  <el-icon><i class="el-icon-search" /></el-icon> 查询
                </el-button>
                <el-button @click="handleReset">
                  <el-icon><i class="el-icon-refresh" /></el-icon> 重置
                </el-button>
              </el-space>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 高级 -->
        <el-row v-show="!folded" :gutter="12" class="mt-2">
          <el-col :xs="24" :sm="12" :md="8" :lg="6">
            <el-form-item label="数量≥(kg)">
              <el-input-number v-model="searchObj.min_quantity" :min="0" :step="1" controls-position="right" style="width:100%" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <!-- 收获记录表格 -->
    <el-card shadow="hover">
      <el-table
          v-loading="loading"
          :data="tableData"
          style="width: 100%"
          stripe
          size="small"
          :header-cell-style="{ background: 'var(--el-fill-color-light)', fontWeight: 600 }"
          :empty-text="'暂无数据'"
      >
        <el-table-column prop="fruit_name" label="水果名称" min-width="130" show-overflow-tooltip />
        <el-table-column prop="harvest_date" label="收获时间" width="180" show-overflow-tooltip>
          <template #default="{ row }">
            {{ formatDateTime(row.harvest_date) }}
          </template>
        </el-table-column>
        <el-table-column prop="batch_no" label="批次号" width="160" show-overflow-tooltip>
          <template #default="{ row }">
            <el-tag type="info" effect="light">{{ row.batch_no }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="quantity" label="收获数量(kg)" width="140" align="right">
          <template #default="{ row }">
            <span class="num">{{ row.quantity }}</span>
          </template>
        </el-table-column>
        <el-table-column label="状态" width="120">
          <template #default="{ row }">
            <el-tag :type="row.isdel === 0 ? 'success' : 'danger'">
              {{ row.isdel === 0 ? '正常' : '已删除' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="220" fixed="right" align="center">
          <template #default="scope">
            <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button
                size="small"
                type="danger"
                @click="handleDelete(scope.row)"
                :disabled="scope.row.isdel !== 0"
            >
              删除
            </el-button>
          </template>
        </el-table-column>

        <template #empty>
          <el-empty description="没有找到相关收获记录">
            <el-button type="primary" text @click="handleAdd">去新增</el-button>
          </el-empty>
        </template>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
            v-model:current-page="searchObj.current"
            v-model:page-size="searchObj.limit"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            :page-sizes="[10, 20, 50, 100]"
            @current-change="loadData"
            @size-change="handleSizeChange"
        />
      </div>
    </el-card>

    <!-- 新增/编辑弹窗 -->
    <el-dialog v-model="dialogVisible" :title="isAdd ? '新增收获记录' : '编辑收获记录'" width="520px">
      <el-form :model="form" :rules="rules" ref="formRef" label-width="110px">
        <el-form-item label="水果" prop="fruit_id">
          <el-select
              v-model="form.fruit_id"
              placeholder="请选择水果"
              filterable
              :loading="fruitLoading"
              style="width: 100%"
          >
            <el-option
                v-for="f in fruits"
                :key="f.fruit_id"
                :label="f.fruit_name"
                :value="f.fruit_id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="收获时间" prop="harvest_date">
          <!-- 表单使用 datetime + value-format 直接双向绑定字符串 -->
          <el-date-picker
              v-model="form.harvest_date"
              type="datetime"
              placeholder="选择收获时间"
              style="width: 100%"
              value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>

        <el-form-item label="批次号" prop="batch_no">
          <el-input v-model="form.batch_no" placeholder="如 2024082001" />
        </el-form-item>

        <el-form-item label="收获数量(kg)" prop="quantity">
          <el-input-number v-model="form.quantity" :min="0.1" :step="0.1" controls-position="right" style="width:100%" />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-space>
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确认提交</el-button>
        </el-space>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { Plus } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import harvestApi from '@/api/harvest_api.js'
import fruitApi from '@/api/fruit_api.js'
import { cloneDeep } from 'lodash'

const folded = ref(true)

// 表格数据
const tableData = ref([])
const total = ref(0)
const loading = ref(false)

// 水果下拉
const fruits = ref([])
const fruitLoading = ref(false)

const loadFruits = async () => {
  fruitLoading.value = true
  try {
    const res = await fruitApi.page({ current: 1, limit: 1000 })
    const arr = res?.data || []
    fruits.value = arr.map(x => ({
      fruit_id: x.fruit_id ?? x.id,
      fruit_name: x.fruit_name ?? x.name
    }))
  } catch (e) {
    console.error('加载水果列表失败: ', e)
  } finally {
    fruitLoading.value = false
  }
}

// 搜索参数（harvest_date 始终为 "YYYY-MM-DD HH:mm:ss" 字符串或空）
const searchObj = ref({
  current: 1,
  limit: 10,
  fruit_id: null,
  harvest_date: '',
  batch_no: '',
  min_quantity: null
})

// 弹窗相关（harvest_date 也是字符串）
const dialogVisible = ref(false)
const isAdd = ref(true)
const formRef = ref()
const form = ref({
  harvest_id: '',
  fruit_id: null,
  harvest_date: '',
  batch_no: '',
  quantity: 0,
  isdel: 0
})

// 校验
const rules = {
  fruit_id: [{ required: true, message: '请选择水果', trigger: 'change' }],
  harvest_date: [{ required: true, message: '请选择收获时间', trigger: 'change' }],
  batch_no: [{ required: true, message: '请输入批次号', trigger: 'blur' }],
  quantity: [
    { required: true, message: '请输入数量', trigger: 'blur' },
    { type: 'number', min: 0.1, message: '数量需大于 0', trigger: 'change' }
  ]
}

// 容错显示：后端若已返回 "yyyy-MM-dd HH:mm:ss" 直接显示；否则尝试解析
const formatDateTime = (input) => {
  if (!input) return ''
  if (typeof input === 'string') {
    // 如果是标准 yyyy-MM-dd HH:mm:ss，直接返回
    if (/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/.test(input)) return input
    // 其他字符串，尝试 new Date 再格式化
    const d = new Date(input)
    if (!isNaN(d)) return toYMDHMS(d)
    return input
  }
  if (input instanceof Date && !isNaN(input)) return toYMDHMS(input)
  return ''
}

const pad2 = (n) => (n < 10 ? '0' + n : '' + n)
const toYMDHMS = (d) => {
  const y = d.getFullYear()
  const m = pad2(d.getMonth() + 1)
  const dd = pad2(d.getDate())
  const hh = pad2(d.getHours())
  const mi = pad2(d.getMinutes())
  const ss = pad2(d.getSeconds())
  return `${y}-${m}-${dd} ${hh}:${mi}:${ss}`
}

const toggleFold = () => { folded.value = !folded.value }

// 重置
const handleReset = () => {
  searchObj.value = {
    current: 1,
    limit: searchObj.value.limit,
    fruit_id: null,
    harvest_date: '',
    batch_no: '',
    min_quantity: null
  }
  loadData()
}

// 加载数据：直接把字符串条件原样传给后端
const loadData = async () => {
  loading.value = true
  try {
    const raw = { ...searchObj.value }
    const params = {}
    Object.keys(raw).forEach(k => {
      const v = raw[k]
      if (v !== '' && v !== null && v !== undefined) params[k] = v
    })
    if (params.fruit_id) params.fruit_id = Number(params.fruit_id)

    const res = await harvestApi.page(params)
    tableData.value = res?.data || []
    total.value = res?.count || 0
  } catch (e) {
    ElMessage.error('加载失败')
    console.error(e)
  } finally {
    loading.value = false
  }
}

// 新增
const handleAdd = () => {
  isAdd.value = true
  form.value = {
    harvest_id: '',
    fruit_id: null,
    harvest_date: '', // 由 datetime 选择器赋值成 "yyyy-MM-dd HH:mm:ss"
    batch_no: '',
    quantity: 0,
    isdel: 0
  }
  dialogVisible.value = true
}

// 编辑：把后端给的值塞回表单（保持字符串格式）
const handleEdit = (row) => {
  isAdd.value = false
  const copy = cloneDeep(row)
  // 如果后端返回的是 Date 可解析字符串，转成 "yyyy-MM-dd HH:mm:ss"
  if (copy.harvest_date && typeof copy.harvest_date !== 'string') {
    const d = new Date(copy.harvest_date)
    copy.harvest_date = isNaN(d) ? '' : toYMDHMS(d)
  } else if (
      copy.harvest_date &&
      typeof copy.harvest_date === 'string' &&
      !/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/.test(copy.harvest_date)
  ) {
    const d = new Date(copy.harvest_date)
    copy.harvest_date = isNaN(d) ? copy.harvest_date : toYMDHMS(d)
  }
  form.value = copy
  dialogVisible.value = true
}

// 提交：payload 中 harvest_date 已是 "yyyy-MM-dd HH:mm:ss" 字符串
const handleSubmit = async () => {
  try {
    await formRef.value.validate()
    const payload = { ...form.value }
    if (payload.fruit_id) payload.fruit_id = Number(payload.fruit_id)

    if (!payload.harvest_date || !/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/.test(payload.harvest_date)) {
      // 兜底：如果是 Date 或其他格式，转成标准格式
      const d = new Date(payload.harvest_date)
      if (!isNaN(d)) payload.harvest_date = toYMDHMS(d)
    }

    if (isAdd.value) {
      await harvestApi.add(payload)
      ElMessage.success('新增成功')
    } else {
      await harvestApi.edit(payload)
      ElMessage.success('编辑成功')
    }
    dialogVisible.value = false
    loadData()
  } catch (error) {
    if (error !== undefined) {
      ElMessage.error(isAdd.value ? '新增失败' : '编辑失败')
      console.error(error)
    }
  }
}

// 删除
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(`确定删除批次【${row.batch_no}】的收获记录吗？`, '警告', {
      type: 'warning',
      draggable: true
    })
    await harvestApi.del(row.harvest_id)
    ElMessage.success('删除成功')
    loadData()
  } catch (error) {
    if (error?.message !== 'cancel') {
      ElMessage.error('删除失败')
      console.error(error)
    }
  }
}

// 分页大小变化
const handleSizeChange = (val) => {
  searchObj.value.limit = val
  searchObj.value.current = 1
  loadData()
}

// 初始化
onMounted(() => {
  loadFruits()
  loadData()
})
</script>

<style scoped>
.harvest-container { padding: 18px; }
.search-card { margin-bottom: 16px; border-radius: 14px; }
.card-header { display: flex; align-items: center; justify-content: space-between; }
.card-header .title { display: flex; align-items: center; gap: 8px; font-weight: 600; }
.card-header .actions { display: flex; gap: 8px; }
.search-form :deep(.el-form-item) { margin-bottom: 12px; }
.mt-2 { margin-top: 8px; }
.pagination { margin-top: 14px; display: flex; justify-content: center; }
.num { font-variant-numeric: tabular-nums; }
</style>
